笔记 nodejs chrome websocket安装和使用过程中遇到的问题

您所在的位置:网站首页 client module没有 笔记 nodejs chrome websocket安装和使用过程中遇到的问题

笔记 nodejs chrome websocket安装和使用过程中遇到的问题

2024-07-14 05:14| 来源: 网络整理| 查看: 265

原理层面的东西就不阐述了,百度能找到很多,这里重点是使用

1.服务端websocket包安装后运行报错

Error: Cannot find module 'websocket'

似乎是初学者常遇到的,虽然是一句

npm install websocket

就能搞定的,但是注意打开方式:不要win+r然后cmd粘贴,可以先cd到服务端目录,在服务端目录里运行,这样可以避免以后版本的兼容性问题

2.文档看的一脸懵逼

扔一边不看算了,拿到官方例程,注意几个地方

#!/usr/bin/env node var WebSocketServer = require('websocket').server; var http = require('http'); var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(8080, function() { console.log((new Date()) + ' Server is listening on port 8080'); }); wsServer = new WebSocketServer({ httpServer: server, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection // facilities built into the protocol and the browser. You should // *always* verify the connection's origin and decide whether or not // to accept it. autoAcceptConnections: false }); function originIsAllowed(origin) { // put logic here to detect whether the specified origin is allowed. return true; } wsServer.on('request', function(request) { if (!originIsAllowed(request.origin)) { // Make sure we only accept requests from an allowed origin request.reject(); console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); return; } var connection = request.accept('echo-protocol', request.origin); console.log((new Date()) + ' Connection accepted.'); connection.on('message', function(message) { if (message.type === 'utf8') { console.log('Received Message: ' + message.utf8Data); connection.sendUTF(message.utf8Data); } else if (message.type === 'binary') { console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); connection.sendBytes(message.binaryData); } }); connection.on('close', function(reasonCode, description) { console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); }); });

后面声明了一堆回调函数

onrequest是客户端请求连接时调用的,参数request中包含请求信息(IP等)

onmessage是客户端发送数据时调用的,比如客户端执行ws.send('hello'),这里的message就会是hello

onclose是客户端断开连接时调用的,不只是调用ws.close(),浏览器窗口直接关闭的时候也会响应(貌似基本上很保险,掉线什么的不需要自己考虑了 还没尝试长时间无响应那种)

客户端(我这里没用官方的 直接上chrome了 随便打开一个网页 然后ctrl+shift+j打开控制台直接干):

var ws=new WebSocket('ws://localhost:8080/','echo-protocol');

然后客户端那边就提示有连接创建了,完美!试一下发消息

ws.send('hello')

服务端那边正确回显,发数组等object也没问题

3.获取所有的客户端

看了好久api文档没看到这种操作,结果官方给的方法就是——弄一个全局数组,在有新的连接创建的时候push进去……

参考链接:获取客户端列表



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3